<script setup>
import { hiprint, defaultElementTypeProvider } from 'vue-plugin-hiprint'
import { GetConfigAPI } from '@/api/system/printConfig'
import View from '@/views/system/printConfig/view.vue'
import useUserStore from '@/store/modules/user'
import dayjs from 'dayjs'
const emit = defineEmits()
const { proxy } = getCurrentInstance()
const useUser = useUserStore()
const props = defineProps({
  // 数据
  printData: {
    type: Object || Array,
    default: () => {}
  },
  // 模板ID
  templateId: {
    type: String || Number,
    default: ''
  },
  copies: {
    type: String || Number,
    default: '1'
  },
  zoom: {
    type: Number,
    default: 1
  }
})

const viewRef = ref(null)

const config = reactive({
  width: '',
  height: '',
  hiprintConfig: '',
  hiprintTemplate: ''
})
const timer = ref(null)
// 获取打印纸宽高
const init = () => {
  console.log('打印内容：=>', props.printData)
  if (!props.printData) return proxy.warningMsg('开发专用打印数据为空')
  if (Array.isArray(props.printData)) {
    props.printData.forEach(item => {
      item.printBy = useUser.name
      item.printTime = dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss')
    })
  } else {
    props.printData.printBy = useUser.name
    props.printData.printTime = dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss')
  }
  config.width = config.hiprintTemplate.panels[0].width + 10
  config.height = config.hiprintTemplate.panels[0].height + 10
  config.hiprintTemplate.panels[0].scale = props.zoom

  config.hiprintConfig = new hiprint.PrintTemplate({ template: config.hiprintTemplate })
  console.log(config.hiprintConfig, 'config.hiprintConfig')
  $('#preview_content_design').html(config.hiprintConfig.getHtml(props.printData))
}

let tiemr = null
// 连接打印机
const printLink = () => {
  tiemr = setInterval(() => {
    if (hiprint.hiwebSocket.opened) {
      clearInterval(tiemr)
      print()
      proxy.successMsg('打印机连接成功！')
      return
    }
    hiprint.hiwebSocket.setHost(import.meta.env.VITE_APP_BASE_PRINT)
  }, 1000)
}

// 打印
const print = async () => {
  if (!props.printData) return proxy.warningMsg('开发专用打印数据为空')
  if (Array.isArray(props.printData)) {
    props.printData.forEach(item => {
      item.printBy = useUser.name
      item.printTime = dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss')
    })
  } else {
    props.printData.printBy = useUser.name
    props.printData.printTime = dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss')
  }
  if (!hiprint.hiwebSocket.opened) {
    hiprint.hiwebSocket.setHost(import.meta.env.VITE_APP_BASE_PRINT)
    // 重新连接客户端  当然你可以去连接局域网内的客户端
    proxy.warningMsg('打印服务没有启动，请运行Hiprint打印软件!')
    return
  }
  await getConfig()
  proxy.$modal.loading('打印中，请稍后...')

  hiprint.refreshPrinterList(list => {})
  // if (1 == 1) {
  //   emit('printYes')
  //   proxy.$modal.closeLoading()
  //   return
  // }
  // 判断是否已成功连接
  if (!hiprint.hiwebSocket.opened) {
    // 重新初始化
    init()
    printLink()
    return
    // hiprint.hiwebSocket.setHost(import.meta.env.VITE_APP_BASE_PRINT)
    // // 重新连接客户端  当然你可以去连接局域网内的客户端
    // proxy.warningMsg('打印机未连接，正在尝试连接')
    // proxy.$modal.closeLoading()
    // return
  }

  if (!props.templateId) {
    proxy.$modal.closeLoading()
    proxy.warningMsg('开发问题,没有给打印组件传入模板id！')
    return
  }
  if (!config?.hiprintConfig?.print2) {
    await getConfig()
    proxy.warningMsg('打印失败,没有找到模板！')
    proxy.$modal.closeLoading()
    return
  }

  console.log(props.printData, 'props.printData=====')

  // config.hiprintTemplate.panels[0].scale = 1
  // config.hiprintConfig = new hiprint.PrintTemplate({ template: config.hiprintTemplate })
  // $('#preview_content_design').html(config.hiprintConfig.getHtml(props.printData))
  config.hiprintConfig.print2(props.printData, {
    setDuplexPrint: false,
    title: '普众联合-打印服务',
    copies: Number(props.copies), // 打印份数 默认 1
    orient: 2
  })

  config.hiprintConfig.on('printSuccess', function (data) {
    setTimeout(() => {
      emit('printYes')
      proxy.successMsg('打印成功' + JSON.stringify(data))
      proxy.$modal.closeLoading()
    }, 1000)
  })

  config.hiprintConfig.on('printError', function (data) {
    setTimeout(() => {
      proxy.warningMsg('打印失败，失败参数：' + JSON.stringify(data))
      proxy.$modal.closeLoading()
    }, 1000)
  })
}

// 预览
const preView = () => {
  if (!props.templateId) return proxy.warningMsg('请选择对应标签')
  config.hiprintTemplate.panels[0].scale = 1
  viewRef.value.isShow1(config.hiprintTemplate, props.printData)
}

// 转PDF
const toPdf = () => {
  hiprintTemplate.toPdf(printConfig.printData, '打印预览pdf')
}

const loading = ref(false)
// 配置 弹窗
const getConfig = async templateId => {
  console.log(templateId, 'templateId')

  loading.value = true
  try {
    const res = await GetConfigAPI(props.templateId || templateId)
    console.log(res, 'res配置 弹窗11')
    config.hiprintTemplate = JSON.parse(res.msg)
    init()
    clearInterval(timer.value)
  } catch {
  } finally {
    loading.value = false
  }
}

watch(
  () => props.templateId,
  val => {
    if (val) getConfig()
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => props.printData,
  val => {
    nextTick(() => {
      if (val && props.templateId) getConfig()
    })
  },
  {
    deep: true,
    immediate: true
  }
)
defineExpose({ print, getConfig })
</script>

<template>
  <div style="width: 100%; overflow-y: auto">
    <div
      v-loading="loading"
      class="print-view"
      @click.stop="preView"
      :style="`height:${config.height || 100}mm;width:${config.width || 150}mm`"
    >
      <el-empty v-if="!props.templateId" description="description" />
      <div v-else id="preview_content_design"></div>
      <View ref="viewRef" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.print-view {
  transition: all 0.2s;

  cursor: pointer;
}

.print-view ::v-deep .hiprint-printPanel {
  border: 2px solid #d2cdcd;
  border-radius: 10px;
  margin-bottom: 0.3125rem;
}
</style>
